package uia.alumni.profile;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.form.Form;
import uia.alumni.form.FormField;
import uia.alumni.web.Command;

import static uia.alumni.profile.Constants.*;
import static uia.alumni.web.Constants.*;
import static uia.alumni.form.FieldType.*;

/**
 * Process the EditPassword form. If everything is ok the new
 * password is saved and the ViewProfile page is displayed.
 * Otherwise the EditPassword form is redisplayed with an error
 * message explaining the problem.
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 * @author (edit) Simon Zimmermann.
 */
public class SavePassword extends Command {

    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "profile.savepassword";
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction tx;

    public SavePassword() {
        super(Role.member);
    }

    /**
     * Save the password from the EditPassword form, IF THE OLD PASSWORD
     * IS CORRECT.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        boolean success = false;

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = getUser(em, request);

            Form form = new Form(request);

            // Check old PW if we're need not Admin
            if(!isAdmin(em, request))
                form.newField(OLDPASSWORD, CUSTOM).setCustomRegex("^"+user.getPassword()+"$");
            FormField newPwd = form.newField(PASSWORD, PW);

            if (form.isValid()) {
                // Check if user entered 2 passwords.
                if (newPwd.getFieldValues().size() == 2) {
                    String p1, p2;
                    p1 = newPwd.getFieldValues().get(0);
                    p2 = newPwd.getFieldValues().get(1);

                    // Check that the new passwords are alike. 
                    if (p1.equals(p2)) {
                        user.setPassword(newPwd.getFieldValue());
                        success = true; // SUCCESS
                        tx.commit();
                    } else {
                        addFormErrors(request, form.addError("New Passwords NOT equal."));
                    }
                } else {
                    addFormErrors(request, form.addError("Insufficient Passwords"));
                }
            } else { // If form Errors.
                form.addError("A password must have 4-20 Chars. [abcABC + Numbers !@#$%^& allowed]");
                addFormErrors(request, form.getErrors());
            }

        } catch (Exception e) {
            addMessage(request, "Password Change Failed because?" + e.getMessage());
        }
        if (success) forwardTo(ViewProfile.SERVLET_NAME, request, response);
        forwardTo(EditPassword.SERVLET_NAME, request, response);
    }
    public final static long serialVersionUID = 1;
}
